package org.HisCanvas.ChrisRiffle.JFlightLog.swingUi.table;

import java.awt.Component;

import javax.swing.JTable;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;

public class TableUtils {


	/**
	 * Sets the preferred width of the visible column specified by vColIndex.
	 * The column will be just wide enough to show the column head margin pixels
	 * are added to the left and right (resulting in an additional width of
	 * 2*margin pixels).
	 */
    public static void packColumn(JTable table, int vColIndex) {
    	
    	int columnMargins = 2; 
    
        DefaultTableColumnModel colModel = (DefaultTableColumnModel)table.getColumnModel();
        
        TableColumn col = colModel.getColumn(vColIndex);
        
        int width = 0;

        // Get width of column header
        TableCellRenderer renderer = col.getHeaderRenderer();
        if (renderer == null) {
            renderer = table.getTableHeader().getDefaultRenderer();
        }
        Component comp = renderer.getTableCellRendererComponent(
            table, col.getHeaderValue(), false, false, 0, 0);
        
        width = comp.getPreferredSize().width;
        
        // Add margin
        width += 2 * columnMargins;
        
        // Set the width
        col.setPreferredWidth(width);
        
        //don't let someone drag the column too small
        col.setMinWidth(width);
    }

}
